package cn.zxw.login;


import cn.zxw.functionset.FunctionApp;
import cn.zxw.functionset.FunctionController;
import cn.zxw.utils.CommenUtils;
import cn.zxw.utils.StringUtil;
import com.jfoenix.controls.JFXCheckBox;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.io.*;
import java.net.URL;
import java.util.Iterator;
import java.util.Properties;
import java.util.ResourceBundle;



/**
 * 功能描述: 登录控制器<br>
 * @Author: zxw
 * @Date: 2020/7/1 10:37
 */
public  class LoginController  implements Initializable {

    private LoginApp application;
    private static int rememberUser = 1;
    private static int rememberLogin = 1;
    public static String projectPath ;//项目路径
    public static double x1;
    public static double y1;
    public static String soundR = "0";
    public static String areatR = "0";
    public static String taskR = "0";
    public static String startR = "0";
    public  CheckBox soundReminder;//声音
    public  CheckBox alertReminder;//弹框
    public  CheckBox taskReminder;//任务栏
    public  CheckBox startUp;//开机启动
    @FXML
    private TextField account;
    @FXML
    private PasswordField password;
    @FXML
    private JFXCheckBox comboBoxMember;//记住用户密码
    @FXML
    private JFXCheckBox comboBoxLogin;//是否自动登录

    public void setApp(LoginApp application) {
        this.application = application;
    }


    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            //获取当前项目路径
            File dir = new File("");// 参数为空
            projectPath = dir.getCanonicalPath()+"/JFXMyclient.exe";//获取项目路径
            System.out.println("projectPath==" + projectPath);
            creatLinkInfo();//动态创建连接信息
            Properties properties = CommenUtils.getProperties("login.properties");
            if(properties!=null){
                String userName = properties.get("userName").toString();
                String passwordf = properties.get("passwordf").toString();
                String login_auto = properties.get("login_auto").toString();//是否自动登录
                String remember_user = properties.get("remember_user").toString();//记住用户名密码
                if(login_auto.equals("true")){
                    comboBoxLogin.setSelected(true);
                }
                if(remember_user.equals("true")){
                    comboBoxMember.setSelected(true);
                    account.setText(userName);
                    password.setText(passwordf);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 点击按钮登录
     * @param event
     */
    @FXML
    protected boolean LOGIN_M(ActionEvent event) {
        final String userName = account.getText();
        final String passwordf = password.getText();
        if (null == userName || "".equals(userName)) {
            showalertInfo("用户名不能为空");
            return false;
        }
        if (null == passwordf || "".equals(passwordf)) {
            showalertInfo("密码不能为空");
            return false;
        }
        rememberUser =comboBoxMember.isSelected() ? 1 : 0;//记住用户名
        rememberLogin =comboBoxLogin.isSelected() ? 1 : 0;//自动登录
        Properties prop = new Properties();
        if (rememberUser == 1) {//选中状态
            if (!userName.isEmpty() && !passwordf.isEmpty()) {
                prop.setProperty("userName", userName);
                prop.setProperty("passwordf", passwordf);
                prop.setProperty("remember_user", "true");
                prop.setProperty("login_auto", "false");
            }
        }else if(rememberUser == 0){//未选中状态
            prop.setProperty("userName", "");
            prop.setProperty("passwordf", "");
            prop.setProperty("remember_user", "false");
            prop.setProperty("login_auto", "false");
        }
        if(rememberLogin==1){
            prop.setProperty("login_auto", "true");
        }
        CommenUtils.writeFile("login.properties",prop);
        Task<Void> task = new Task<Void>() {
                @Override
                public Void call() throws InterruptedException {
                    try {
                        application.userLogin(userName.toString(), passwordf.toString());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return null;
                }
            };
            new Thread(task).start();
            return true;
    }



    //关闭
    @FXML
    public void close() {
        try {
            LoginApp.stage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //功能设置
    @FXML
    public void shezhi(MouseEvent m) {
        try {
            Stage stage = getStage();
            //双击事件方法
            x1 =m.getScreenX();
            y1 =m.getScreenY();
            stage.setX(x1-148);
            stage.setY(y1);
            stage.show();
            Thread thread = new Thread(() -> {
                try {
                    Thread.sleep(5000);
                    if (stage.isShowing()) {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run()  {
                                setValue(soundR,areatR,taskR,startR);//调用赋值的方法
                                stage.close();
                            }
                        });
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            });
            thread.setDaemon(true);
            thread.start();
            getValue();
        } catch (Exception x) {
            x.printStackTrace();
        }
    }


    //获取设置的弹框
    public Stage getStage() {
        Stage functionStage=new Stage();
        Pane stackPane = new Pane();
        stackPane.setPrefWidth(148.0);
        stackPane.setPrefHeight(129.0);

        alertReminder = new CheckBox();
        alertReminder.setLayoutX(10);
        alertReminder.setLayoutY(15);
        alertReminder.setText("屏蔽弹窗提醒");
        alertReminder.setTextFill(Color.web("#726c6c"));

        taskReminder = new CheckBox();
        taskReminder.setLayoutX(10);
        taskReminder.setLayoutY(40);
        taskReminder.setText("屏蔽任务栏提醒");
        taskReminder.setTextFill(Color.web("#726c6c"));

        soundReminder = new CheckBox();
        soundReminder.setLayoutX(10);
        soundReminder.setLayoutY(65);
        soundReminder.setText("屏蔽声音提醒");
        soundReminder.setTextFill(Color.web("#726c6c"));

        startUp = new CheckBox();
        startUp.setLayoutX(10);
        startUp.setLayoutY(90);
        startUp.setText("开机自动启动");
        startUp.setTextFill(Color.web("#726c6c"));

        stackPane.getChildren().add(alertReminder);
        stackPane.getChildren().add(taskReminder);
        stackPane.getChildren().add(soundReminder);
        stackPane.getChildren().add(startUp);

        Scene scene=new Scene(stackPane);
        functionStage.setScene(scene);
        functionStage.initStyle(StageStyle.TRANSPARENT);
        functionStage.show();
        // getValue();
        //用于监听选择框
        soundReminder.selectedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> ov,
                                Boolean old_val, Boolean new_val) {
                System.out.println(soundReminder.isSelected());
                soundR =soundReminder.isSelected() ?"1" : "0";//1是选中  0是未选中
            }
        });
        alertReminder.selectedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> ov,
                                Boolean old_val, Boolean new_val) {
                System.out.println(alertReminder.isSelected());
                areatR =alertReminder.isSelected() ?"1" : "0";
            }
        });
        taskReminder.selectedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> ov,
                                Boolean old_val, Boolean new_val) {
                System.out.println(taskReminder.isSelected());
                taskR =taskReminder.isSelected() ?"1" : "0";
            }
        });
        startUp.selectedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> ov,
                                Boolean old_val, Boolean new_val) {
                System.out.println(startUp.isSelected());
                startR =startUp.isSelected() ?"1" : "0";
                String projectPath = LoginController.projectPath;
                if(!startR.equals("1")){
                    new CommenUtils().setAutoStart(true,projectPath);//开机自启动
                }else{
                    new CommenUtils().setAutoStart(false,projectPath);//开机自启动
                }
            }
        });

        //鼠标离开
        scene.setOnMouseExited(new EventHandler<MouseEvent>() {
            @Override public void handle(javafx.scene.input.MouseEvent m) {
                setValue(soundR,areatR,taskR,startR);//调用赋值的方法
                functionStage.close();
            }
        });

        return functionStage;
    }




    @FXML
    public void min() {
        LoginApp.stage.setIconified(true);
    }




    public static void showalertInfo(String msg){
        new Alert(Alert.AlertType.NONE, msg, new ButtonType[]{ButtonType.CLOSE}).show();
    }



    //赋值方法--写入
    public  static void setValue(String soundR,String areatR,String taskR,String startR){
        Properties prop = new Properties();
        prop.setProperty("soundR", soundR);
        prop.setProperty("areatR", areatR);
        prop.setProperty("taskR", taskR);
        prop.setProperty("startR", startR);
        CommenUtils.writeFile("setting.properties",prop);

    }


    //获取赋值方法
    public  void getValue(){
        Properties properties = CommenUtils.getProperties("setting.properties");
        soundR =(String)properties.get("soundR");
        areatR =(String)properties.get("areatR");
        taskR = (String)properties.get("taskR");
        startR =(String) properties.get("startR");
        if(soundR.equals("1")){
            soundReminder.setSelected(true);
        }
        if(areatR.equals("1")){
            alertReminder.setSelected(true);
        }
        if(taskR.equals("1")){
            taskReminder.setSelected(true);
        }
        if(startR.equals("1")){
            startUp.setSelected(true);
        }

    }

    //创建连接配置--可动态修改 暂时写死
    public static void creatLinkInfo(){
        Properties properties = CommenUtils.getProperties("plugin.properties");
        if(properties==null){
            Properties prop = new Properties();
            String ip="XX.XX.XX.XX";
            prop.setProperty("host", ip);
            prop.setProperty("port", "6667");
            prop.setProperty("notic_ip", "http://"+ip+":3000/#/notify/OaNotifyList");
            CommenUtils.writeFile("plugin.properties",prop);
        }
    }
}
